export const GET = "GET";
export const POST = "POST";
export const PUT = "PUT";
export const PATCH = "PATCH";
export const DELETE = "DELETE";

/**
 * 对 fetch 异步网络请求封装
 * 请求成功返回 Promise 对象
 * 请求异常时进行处理
 */
export default async function api(url, method=GET, data={}) {
  const response = await request(url, method, data);
  return await response.json();
}

function request(url, method, data) {
  return new Promise(
    (resolve, _) => {
      let promise;
      // 1. 执行异步请求
      switch (method) {
        case GET:
        case DELETE:
          promise = fetch(url + new URLSearchParams(data));
          break;
        case POST:
        case PUT:
        case PATCH:
          promise = fetch(
            url,
            {
              method,
              headers: {'Content-Type': 'application/json;charset=utf-8'},
              body: JSON.stringify(data)
            }
          );
          break;
        default:
          console.log(`[ajax] 网络请求未发送, 因为不支持的请求方法: url=${url}, method=${method}`);
          return;
      }
      // 2. 如果成功了, 调用 resolve(value)
      promise.then(response => {
        // console.log(`[ajax] 网络请求成功: url=${url}, method=${method}, data=`, data, `result=`,response);
        resolve(response)
      })
      // 3. 如果失败了, 不调用reject(reason), 而是提示异常信息
      .catch(error => {
        console.log(`[ajax] 网络请求失败: url=${url}, method=${method}, error=`, error);
      });
    }
  );
}